//
//  XGWebViewController.m
//  BSBuDeJie
//
//  Created by monkey on 2018/12/16.
//  Copyright © 2018 itcast. All rights reserved.
//

#import <WebKit/WebKit.h>

#import "XGWebViewController.h"

/// 底部菜单栏高度
static const CGFloat kBottomToolBarHeight = 49.f;

@interface XGWebViewController () <WKNavigationDelegate>

/// webView
@property (nonatomic,strong) WKWebView *webView;
/// 进度条
@property (nonatomic,strong) UIProgressView *progressView;
/// 工具栏
@property (nonatomic,strong) UIToolbar *toolBar;

@end

@implementation XGWebViewController
{
    /// 请求地址
    NSURL *_url;
}

#pragma mark - 构造方法

- (instancetype)initWithURL:(NSURL *)url
{
    // super仅仅是调用父类方法 并不是指父类 如果是[super init] 会调用本类的initWithNibName:bundle:方法
    if (self = [super initWithNibName:nil bundle:nil]) {
        if (url == nil) {
            NSException *exp = [NSException exceptionWithName:@"参数错误!" reason:@"URL不能为空!!!" userInfo:nil];
            [exp raise];
            return nil;
        } else {
            _url = url;
            _isShowProgress = YES;
            _isShowBottomToolbar = YES;
        }
    }
    
    return self;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    NSException *exp = [NSException exceptionWithName:@"XGWebViewController创建错误!" reason:@"请使用-initWithURL:或+webViewControllerWithURL:方法创建XGWebViewController" userInfo:nil];
    [exp raise];
    return nil;
}

+ (instancetype)webViewControllerWithURL:(NSURL *)url
{
    return [[self alloc] initWithURL:url];
}

#pragma mark - 控制器生命周期方法

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 设置导航栏
    [self setUpNavigationItem];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // 设置视图层次结构
    [self setUpUI];
    // 加载网络请求
    [self loadRequest];
}

- (void)dealloc
{
    // 移除KVO监听 title 标题 estimatedProgress 进度 canGoBack 前进 canGoForward 后退
    if (self.navigationController != nil) {
        [self.webView removeObserver:self forKeyPath:@"title"];
    }
    
    if (_isShowProgress) {
        [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    }
    
    if (_isShowBottomToolbar) {
        [self.webView removeObserver:self forKeyPath:@"canGoBack"];
        [self.webView removeObserver:self forKeyPath:@"canGoForward"];
    }
}

#pragma mark - 事件监听

- (void)goBackAction
{
    [self.webView goBack];
}

- (void)goForwardAction
{
    [self.webView goForward];
}

- (void)refreshAction
{
    [self.webView reload];
}

- (void)gobackAction
{
    if ([self.delegate respondsToSelector:@selector(webViewControllerGoBackAction:)]) {
        [self.delegate webViewControllerGoBackAction:self];
    }
}

#pragma mark - 系统其他方法

// KVO监听
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    //  title 标题 estimatedProgress 进度 canGoBack 前进 canGoForward 后退
    if ([keyPath isEqualToString:@"title"]) {
        self.navigationItem.title = change[NSKeyValueChangeNewKey];
    } else if ([keyPath isEqualToString:@"canGoBack"]) {
        self.toolBar.items[0].enabled = [change[NSKeyValueChangeNewKey] boolValue];
    } else if ([keyPath isEqualToString:@"canGoForward"]) {
        self.toolBar.items[1].enabled = [change[NSKeyValueChangeNewKey] boolValue];
    }else if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.progress = [change[NSKeyValueChangeNewKey] doubleValue];
    }
}

#pragma mark - 内部其他私有方法

- (void)setUpUI
{
    self.view.backgroundColor = [UIColor whiteColor];

    BOOL isHaveNavigationBar = self.navigationController != nil; // 是否有导航栏
    
    // 添加子控件
    [self.view addSubview:self.webView];
    CGFloat y = isHaveNavigationBar ? self.navigationController.navigationBar.bounds.size.height + 20.f : 0;
    CGFloat height = _isShowBottomToolbar ? self.view.bounds.size.height - kBottomToolBarHeight - y : self.view.bounds.size.height - y;
    self.webView.frame = CGRectMake(0, y, self.view.bounds.size.width, height);
    
    if (_isShowProgress) {
        [self.view addSubview:self.progressView];
        self.progressView.frame = CGRectMake(0, y, self.view.bounds.size.width, 0);
    }
    
    if (_isShowBottomToolbar) {
        // 设置工具栏
        [self setUpToolBar];
        [self.view addSubview:self.toolBar];
        self.toolBar.frame = CGRectMake(0, self.view.bounds.size.height - kBottomToolBarHeight, self.view.bounds.size.width, kBottomToolBarHeight);
    }
}

// 设置工具栏
- (void)setUpToolBar
{
    UIBarButtonItem *goBackItem = [[UIBarButtonItem alloc] initWithTitle:@"后退" style:UIBarButtonItemStylePlain target:self action:@selector(goBackAction)];
    UIBarButtonItem *goForwardItem = [[UIBarButtonItem alloc] initWithTitle:@"前进" style:UIBarButtonItemStylePlain target:self action:@selector(goForwardAction)];
    UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *refreshItem = [[UIBarButtonItem alloc] initWithTitle:@"刷新" style:UIBarButtonItemStylePlain target:self action:@selector(refreshAction)];
    
    goBackItem.enabled = NO;
    goForwardItem.enabled = NO;
    self.toolBar.items = @[goBackItem,goForwardItem,flexibleSpace,refreshItem];
}

- (void)setUpNavigationItem
{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(gobackAction)];
}

- (void)loadRequest
{
    NSURLRequest *request = [NSURLRequest requestWithURL:_url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
    [self.webView loadRequest:request];
    
    // title 标题 estimatedProgress 进度 canGoBack 前进 canGoForward 后退
    // KVO监听
    if (self.navigationController != nil) {
        [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    }
    
    if (_isShowProgress) {
        [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    }
    
    if (_isShowBottomToolbar) {
        [self.webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:nil];
        [self.webView addObserver:self forKeyPath:@"canGoForward" options:NSKeyValueObservingOptionNew context:nil];
    }
}

#pragma mark - WKNavigationDelegate

// 开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    if (_isShowProgress) {
        self.progressView.hidden = NO;
    }
}

// 结束加载
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    if (_isShowProgress) {
        self.progressView.hidden = YES;
    }
}

#pragma mark - 懒加载

- (WKWebView *)webView
{
    if (_webView == nil) {
        _webView = [[WKWebView alloc] init];
        _webView.navigationDelegate = self;
    }
    
    return _webView;
}

- (UIToolbar *)toolBar
{
    if (_toolBar == nil) {
        _toolBar = [[UIToolbar alloc] init];
    }
    
    return _toolBar;
}

- (UIProgressView *)progressView
{
    if (_progressView == nil) {
        _progressView = [[UIProgressView alloc] init];
    }
    
    return _progressView;
}

@end
